import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_taotaoshipin/app/app_controller.dart';
import 'package:flutter_taotaoshipin/common/theme/app_colors.dart';
import 'package:flutter_taotaoshipin/pages/purchase/purchase_type.dart';
import 'package:flutter_taotaoshipin/pages/purchase/subscription/subscription_item.dart';
import 'package:flutter_taotaoshipin/util/apple_pay_utils.dart';
import 'package:flutter_taotaoshipin/util/format_utils.dart';
import 'package:flutter_taotaoshipin/util/global.dart';
import 'package:flutter_taotaoshipin/util/image_utils.dart';
import 'package:flutter_taotaoshipin/value/sp_key.dart';
import 'package:flutter_taotaoshipin/widget/load_image.dart';
import 'package:flutter_taotaoshipin/widget/my_app_bar.dart';
import 'package:flutter_taotaoshipin/widget/my_scroll_view.dart';
import 'package:flutter_taotaoshipin/widget/refresh_header.dart';
import 'package:flutter_taotaoshipin/widget/refresh_status_view.dart';
import 'package:flutter_timer_countdown/flutter_timer_countdown.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'subscription_controller.dart';

class SubscriptionPage extends StatefulWidget {
  const SubscriptionPage({Key? key}) : super(key: key);

  @override
  State<SubscriptionPage> createState() => _SubscriptionPageState();
}

class _SubscriptionPageState extends State<SubscriptionPage> {
  final controller = Get.find<SubscriptionController>();
  final state = Get.find<SubscriptionController>().state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: controller.showNavBack
          ? MyAppBar(
              backgroundColor: Colors.transparent,
              hideLine: true,
            )
          : null,
      extendBodyBehindAppBar: true,
      backgroundColor: Colors.white,
      body: RefreshStatusView(
        controller: controller,
        contentBuilder: (_) {
          return SmartRefresher(
            controller: controller.refreshController,
            // 下拉刷新
            enablePullDown: true,
            header: const RefreshHeader(),
            onRefresh: controller.onRefresh,
            child: CustomScrollView(
              slivers: [
                _buildHeader(),
                _buildGoodsList(),
                _buildCutdownTime(),
                // _buildGoodTop(),
                _buildVipCoinBar(),
                _buildPayButton(),
                _buildAgreement(),
                _buildDecsription(),
                _buildRestorePurchase(),
              ],
            ),
          );
        },
      ),
    );
  }

  _buildHeader() {
    return DecoratedSliver(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: ImageUtils.getAssetImage('subscription/header'),
          fit: BoxFit.fitWidth,
          alignment: Alignment.topCenter,
        ),
      ),
      sliver: SliverToBoxAdapter(
        child: Column(
          children: [
            SizedBox(height: 101.w),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 30),
              child: Row(
                children: [
                  GetBuilder<AppController>(builder: (controller) {
                    return Stack(
                      clipBehavior: Clip.none,
                      children: [
                        LoadAssetImage(
                          'me/avatar',
                          width: 73,
                          height: 73,
                        ),
                        if (isVip())
                          Positioned(
                            left: 20,
                            right: 20,
                            bottom: -3,
                            child: LoadAssetImage(
                              'me/vip_tag',
                              width: 30,
                              height: 12,
                            ),
                          ),
                      ],
                    );
                  }),
                  SizedBox(width: 13.5),
                  GetBuilder<AppController>(
                    builder: (controller) {
                      var user = '开通会员';
                      if (controller.userinfoCenterEntity.mobile!.isNotEmpty) {
                        user = TextUtil.hideNumber(
                            controller.userinfoCenterEntity.mobile!);
                      }
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            user,
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          SizedBox(height: 5),
                          Text(
                            'id:${controller.userinfoCenterEntity.id}',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                              fontWeight: FontWeight.normal,
                            ),
                          ),
                        ],
                      );
                    },
                  ),
                ],
              ),
            ),
            SizedBox(height: 33.w),
            Container(
              width: double.infinity,
              height: 20,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
              ),
            ),
          ],
        ),
      ),
    );
  }

  _buildGoodsList() {
    return SliverToBoxAdapter(
      child: GetBuilder<SubscriptionController>(
          id: 'selected_item',
          builder: (controller) {
            var isSub =
                state.currGood?.goodsType == PurchaseType.subscription.value;
            var each = daysToCycleTime(state.currGood?.days ?? 0);
            var amount = MoneyUtil.changeYWithUnit(
                state.currGood?.amount ?? 0, MoneyUnit.YUAN,
                format: MoneyFormat.END_INTEGER);
            var subAmount = MoneyUtil.changeYWithUnit(
                state.currGood?.subAmount ?? 0, MoneyUnit.YUAN,
                format: MoneyFormat.END_INTEGER);
            return Column(
              children: [
                Container(
                  width: double.infinity,
                  height: 133,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius:
                        BorderRadius.vertical(top: Radius.circular(20)),
                  ),
                  child: GridView.builder(
                    scrollDirection: Axis.horizontal,
                    padding: EdgeInsets.fromLTRB(17, 10, 17, 0),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 1,
                      mainAxisSpacing: 9,
                      crossAxisSpacing: 9,
                      mainAxisExtent: 146,
                    ),
                    itemBuilder: (context, index) {
                      var model = state.goodsList[index];
                      return SubscriptionItem(
                        entity: model,
                        isSelected: state.currGood == model,
                        isSubscripted: state.isSubscripted,
                        onTap: () {
                          controller.itemClicked(model);
                        },
                      );
                    },
                    itemCount: state.goodsList.length,
                  ),
                ),
                Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.all(17),
                  child: Text(
                    isSub
                        ? '首$each$amount到期按照$subAmount自动续费，可随时取消'
                        : '${state.currGood?.name}',
                    style: TextStyle(
                      color: AppColors.text,
                      fontSize: 12,
                    ),
                  ),
                ),
              ],
            );
          }),
    );
  }

  _buildCutdownTime() {
    return GetBuilder<SubscriptionController>(
        id: 'isSubscripted',
        builder: (controller) {
          if (state.isSubscripted) {
            return const SliverToBoxAdapter();
          }
          int lastTime = SpUtil.getInt(SpKey.lastSubDiscountEnterTime)!;
          int remainingSec = 24 * 60 * 60 * 1000;
          int nowTime = DateUtil.getNowDateMs();
          if (DateUtil.isToday(lastTime)) {
            remainingSec -= nowTime - lastTime;
          } else {
            SpUtil.putInt(SpKey.lastSubDiscountEnterTime, nowTime);
          }
          return SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(17, 0, 17, 17),
              child: Container(
                width: double.infinity,
                height: 51,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8),
                  boxShadow: [
                    BoxShadow(
                      color: Color(0x522B5DFF),
                      blurRadius: 2,
                      offset: Offset(0, 0),
                    ),
                  ],
                ),
                child: Row(
                  children: [
                    SizedBox(width: 8),
                    LoadAssetImage(
                      'subscription/ticket',
                      width: 20,
                    ),
                    SizedBox(width: 6),
                    Text(
                      '限时立减券',
                      style: TextStyle(
                        color: Color(0xFF000000),
                        fontSize: 14,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                    SizedBox(width: 8),
                    Expanded(
                      child: Row(
                        children: [
                          TimerCountdown(
                            format: CountDownTimerFormat.hoursMinutesSeconds,
                            endTime: DateTime.now()
                                .add(Duration(milliseconds: remainingSec)),
                            enableDescriptions: false,
                            colonsTextStyle: TextStyle(
                              color: Color(0xFFFF0024),
                              fontSize: 12,
                            ),
                            timeTextStyle: TextStyle(
                              color: Color(0xFFFF0024),
                              fontSize: 12,
                            ),
                            spacerWidth: 0,
                          ),
                          Text(
                            '后失效',
                            style: TextStyle(
                              color: Color(0xFFFF0024),
                              fontSize: 12,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Text(
                      '减免后低至¥',
                      style: TextStyle(
                        color: Color(0xFFFF0024),
                        fontSize: 12,
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(0, 2, 0, 6),
                      child: Text(
                        MoneyUtil.changeYWithUnit(
                            state.pinnedGood?.amount ?? 0, MoneyUnit.NORMAL,
                            format: MoneyFormat.END_INTEGER),
                        style: TextStyle(
                          color: Color(0xFFFF0024),
                          fontSize: 20,
                          fontWeight: FontWeight.w900,
                        ),
                      ),
                    ),
                    SizedBox(width: 22),
                  ],
                ),
              ),
            ),
          );
        });
  }

  _buildGoodTop() {
    if (state.pinnedGood == null) {
      return SliverToBoxAdapter();
    }
    return SliverToBoxAdapter(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(17, 0, 17, 0),
        child: Stack(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 10),
              child: GestureDetector(
                onTap: () {
                  if (!state.isSubscripted) {
                    controller.payButtonClicked(isPinned: true);
                  }
                },
                child: AspectRatio(
                  aspectRatio: 342 / 115,
                  child: Container(
                    decoration: BoxDecoration(
                      image: DecorationImage(
                          image: ImageUtils.getAssetImage(
                              'subscription/top_item_bg')),
                    ),
                    child: Row(
                      children: [
                        SizedBox(width: 13),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Row(
                                children: [
                                  Text.rich(
                                    TextSpan(
                                      text:
                                          '首${daysToCycleTime(state.pinnedGood!.days!)}',
                                      style: TextStyle(
                                        fontSize: 24,
                                        fontWeight: FontWeight.bold,
                                        color: Colors.white,
                                      ),
                                      children: [
                                        TextSpan(
                                          text: MoneyUtil.changeYWithUnit(
                                              state.pinnedGood!.amount!,
                                              MoneyUnit.YUAN,
                                              format: MoneyFormat.END_INTEGER),
                                        ),
                                        TextSpan(
                                          text: '（每人仅限1次）',
                                          style: TextStyle(
                                            fontSize: 12,
                                            fontWeight: FontWeight.w400,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                              Text(
                                '畅看全部短剧剧集',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18,
                                ),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(width: 9),
                        Container(
                          padding:
                              EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Text(
                            '立即开通',
                            style: TextStyle(
                              color: Color(0xFF012078),
                              fontSize: 14,
                              fontWeight: FontWeight.w900,
                            ),
                          ),
                        ),
                        SizedBox(width: 16),
                      ],
                    ),
                  ),
                ),
              ),
            ),
            LoadAssetImage(
              'subscription/new_gift_tag',
              width: 77,
              height: 21,
            ),
          ],
        ),
      ),
    );
  }

  _buildVipCoinBar() {
    return SliverToBoxAdapter(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(17, 0, 17, 0),
        child: AspectRatio(
          aspectRatio: 342 / 115,
          child: Container(
            padding: EdgeInsets.only(left: 26),
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: ImageUtils.getAssetImage('subscription/top_item_bg')),
            ),
            child: GetBuilder<AppController>(builder: (_) {
              String viptime = DateUtil.formatDateMs(
                  (_.userinfoCenterEntity.plusExpire ?? 0) * 1000,
                  format: 'yyyy.MM.dd');
              int coin = _.userinfoCenterEntity.money! +
                  _.userinfoCenterEntity.giveMoney!;
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Row(
                    children: [
                      Row(
                        children: [
                          LoadAssetImage(
                            'me/vip',
                            width: 16,
                            height: 16,
                          ),
                          SizedBox(width: 10),
                          Text(
                            isVip() ? '$viptime到期' : '开通会员，解锁会员特权',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  SizedBox(height: 15),
                  Row(
                    children: [
                      Row(
                        children: [
                          LoadAssetImage(
                            'me/coin',
                            width: 16,
                          ),
                          SizedBox(width: 10),
                          Text(
                            '金币： $coin',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                            ),
                          ),
                        ],
                      )
                    ],
                  ),
                ],
              );
            }),
          ),
        ),
      ),
    );
  }

  _buildPayButton() {
    if (state.currGood == null) {
      return SliverToBoxAdapter();
    }
    return SliverToBoxAdapter(
      child: GetBuilder<SubscriptionController>(
        id: 'selected_item',
        builder: (controller) {
          return Padding(
            padding: const EdgeInsets.only(top: 24),
            child: GestureDetector(
              onTap: () {
                controller.payButtonClicked();
              },
              child: Container(
                width: double.infinity,
                height: 50,
                margin: EdgeInsets.symmetric(horizontal: 17),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      Color(0xFF7AB3FF),
                      Color(0xFF2760FF),
                    ],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: Color(0x993972FF),
                      offset: Offset(0, 5),
                      blurRadius: 10,
                    ),
                  ],
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Text(
                  '¥${MoneyUtil.changeYWithUnit(state.isSubscripted ? state.currGood!.subAmount! : state.currGood!.amount!, MoneyUnit.NORMAL, format: MoneyFormat.END_INTEGER)}立即开通',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.w900,
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  _buildAgreement() {
    return SliverToBoxAdapter(
      child: GestureDetector(
        onTap: () {
          controller.agreePrivacyBtnClicked();
        },
        child: Padding(
          padding: const EdgeInsets.only(top: 30, bottom: 20),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GetBuilder<SubscriptionController>(
                  id: 'privacy_agreement',
                  builder: (controller) {
                    return LoadAssetImage(
                      state.isAgreePrivacy
                          ? 'subscription/agree_sel'
                          : 'subscription/agree_normal',
                      width: 14,
                    );
                  }),
              SizedBox(width: 5),
              RichText(
                text: TextSpan(
                  text: "我同意",
                  style: TextStyle(color: AppColors.text_gray, fontSize: 12),
                  children: [
                    TextSpan(
                      text: "《会员用户协议》",
                      style: TextStyle(color: AppColors.app_main),
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          Global.openVipUserProtocol();
                        },
                    ),
                    TextSpan(text: '和'),
                    TextSpan(
                      text: "《自动续费服务规则》",
                      style: TextStyle(color: AppColors.app_main),
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          Global.openAutoRenewPolicy();
                        },
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _buildDecsription() {
    return SliverToBoxAdapter(
      child: Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.fromLTRB(17, 0, 17, 17),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '''1、付款时向您的 Apple lD 账户收取费用；''',
              style: TextStyle(
                color: AppColors.text_gray,
                fontSize: 10,
                letterSpacing: 0.5,
                height: 1.5,
              ),
            ),
            Text(
              '''2、订阅到期或免费试用结束前 24 小时内，将按页面价格自动续订所选套餐时长；同一 ApplelD 仅能享有一次免费试用资格；''',
              style: TextStyle(
                color: AppColors.text_gray,
                fontSize: 10,
                letterSpacing: 0.5,
                height: 1.5,
              ),
            ),
            Text(
              '''3、如需取消自动续订需在当前订阅周期结束至少 24 小时以前在 iTunes Store 设置中关闭自动续订服务。''',
              style: TextStyle(
                color: AppColors.text_gray,
                fontSize: 10,
                letterSpacing: 0.5,
                height: 1.5,
              ),
            ),
          ],
        ),
      ),
    );
  }

  _buildRestorePurchase() {
    return SliverToBoxAdapter(
      child: Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.fromLTRB(17, 0, 17, 17),
        child: Text.rich(
          TextSpan(
            text: '如果您遇到未发货的问题，请点击',
            style: TextStyle(
              color: AppColors.text_gray,
              fontSize: 10,
              letterSpacing: 0.5,
              height: 1.5,
            ),
            children: [
              TextSpan(
                text: '恢复购买',
                style: TextStyle(color: AppColors.app_main),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    applePayUtils.restorePurchase();
                  },
              ),
              TextSpan(text: '。如果还未解决，请联系客服。'),
            ],
          ),
        ),
      ),
    );
  }
}
